
// 初始化
checkActive();
// 初始化个人信息
updateUserInfo();
// 初始化时间
updateLocalTime();
// 定时器，每秒更新一次时间
setInterval(updateLocalTime, 1000);

let dataArray = [
    {
        "destinationPort": "139",
        "flowDuration": "48 ms",
        "flowRate": "166666.6667 MB/s",
        "packetRate": "83333.33333 p/s",
        "synFlagCount": "0",
        "rstFlagCount": "0",
        "ackFlagCount": "1",
        "eventTime": "2025-03-17 11:33:39",
        "label": "BENIGN"
    },
    {
        "destinationPort": "53",
        "flowDuration": "217 ms",
        "flowRate": "1502304.147 MB/s",
        "packetRate": "18433.17972 p/s",
        "synFlagCount": "0",
        "rstFlagCount": "0",
        "ackFlagCount": "0",
        "eventTime": "2025-03-15 16:53:06",
        "label": "BENIGN"
    }]; // 异常列表数据

// 监听左边栏
document.getElementById('left-bar').addEventListener('click', function (e) {

    if (e.target.closest('.menu-item')) {
        var items = document.querySelectorAll('#left-bar .menu-item');
        for (var item of items) {
            item.classList.remove('selected');
        }
        e.target.closest('.menu-item').classList.add('selected');
        let target = document.getElementById('dashboard');
        switch (e.target.closest('.menu-item').title) {
            case '仪表盘':
                target = document.getElementById('dashboard');
                break;
            case '数据监控':
                target = document.getElementById('data-monitor');
                updateDataMonitor(); // 更新数据监控
                break;
            case '异常分析':
                target = document.getElementById('anomaly-analysis');
                getAndUpdateAnomalyTable(); // 获取并更新异常列表
                break;
        }
        let container = document.getElementById('container-window');
        container.scrollTo(0, target.offsetTop - container.offsetTop);
    }

    if (e.target.closest('BUTTON')) {
        switch (e.target.closest('BUTTON').title) {
            case '登出':
                localStorage.removeItem('lastActiveTime');
                window.location.href = './login.html';
                break;
            case '修改密码':
                openDialog('修改密码');
                break;
            case '修改邮箱':
                openDialog('修改邮箱');
                break;
            case '上传文件':
                window.location.href = './uploadFile.html';
                break;
            default:
                alert('请选择正确的按钮');
                break;
        }
    }
});


// 监听当前异常列表页
document.getElementById('current-page').addEventListener('input', function (e) {
    let page = document.getElementById('current-page')
        .innerText.replace(/[^0-9]/g, '');
    page = page === '' ? 1 : parseInt(page);
    updatePage(page);
});

// 更新页码
function updatePage(page) {
    let max_page = document.getElementById('max-page').innerText;
    max_page = parseInt(max_page);
    if (page < 1) {
        page = 1;
    }
    if (page > max_page) {
        page = max_page;
    }
    // 更新当前页码
    document.getElementById('current-page').innerText = page;
    // 更新页码按钮
    document.getElementById('prev-page').disabled = page === 1;
    document.getElementById('next-page').disabled = page === max_page;
    // 更新异常列表
    updateAnomalyTable();
}

// 监听上一页
document.getElementById('prev-page').addEventListener('click', function (e) {
    let page = document.getElementById('current-page').innerText;
    updatePage(parseInt(page) - 1);
});

// 监听下一页
document.getElementById('next-page').addEventListener('click', function (e) {
    let page = document.getElementById('current-page').innerText;
    updatePage(parseInt(page) + 1);
});

// 监听异常列表
document.getElementById('anomaly-table').addEventListener('click', function (e) {
    if (e.target.closest('.a-text')) {
        let index = e.target.closest('.a-text').dataset.index;
        getAnomalyDetails(index);
        openDialog('异常详情');
    }
});

// 监听阻断IP按钮
document.getElementById('ban-ip-button').addEventListener('click', function (e) {
    openDialog('阻断IP');
});

// 监听白名单按钮
document.getElementById('white-list-button').addEventListener('click', function (e) {
    openDialog('白名单');
});

// 打开弹窗
function openDialog(type) {
    const dialogTitle = document.getElementById('dialog-title');
    const dialogContents = document.getElementById('dialog-body').children;
    for (let content of dialogContents) {
        content.classList.add('hidden');
    }
    switch (type) {
        case '异常详情':
            dialogTitle.innerText = '异常详情';
            document.getElementById('anomaly-details').classList.remove('hidden');
            break;
        case '阻断IP':
            dialogTitle.innerText = '阻断IP';
            document.getElementById('ban-ip').classList.remove('hidden');
            break;
        case '白名单':
            document.getElementById('white-list').classList.remove('hidden');
            dialogTitle.innerText = '白名单';
            break;
        case '修改密码':
            dialogTitle.innerText = '修改密码';
            document.getElementById('change-password').classList.remove('hidden');
            break;
        case '修改邮箱':
            dialogTitle.innerText = '修改邮箱';
            document.getElementById('change-email').classList.remove('hidden');
            document.getElementById('username-input').setAttribute('placeholder', localStorage.getItem('username'));
            break;
    }

    document.getElementById('dialog').showModal();
}

// 监听弹窗
document.getElementById('dialog').addEventListener('click', function (e) {
    if (e.target.closest('.close-dialog')) {
        document.getElementById('dialog').close();
    } else if (e.target.closest('#change-password button')) {
        changePassword();
    } else if (e.target.closest('#change-email button')) {
        changeEmail();
    }
})

// 监听导出按钮
document.getElementById('downfile').addEventListener('click', function (e) {
    let data = document.getElementById('anomaly-details-content').innerText;
    let filename = '异常详情.txt';
    // 创建 Blob 对象
    var blob = new Blob([data], { type: 'text/plain' });
    // 创建 URL
    var url = URL.createObjectURL(blob);
    // 创建 a 标签
    var a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
});

// 监听阻断IP按钮
document.querySelector('#ban-ip button').addEventListener('click', function (e) {
    let ip = document.querySelector('#ban-ip input').value;
    if (!isIp(ip)) {
        alert('IP 地址不合法');
        return;
    }
    // 获取当前时间
    let date = new Date();

    // 添加表格
    let newRecord = `<tr>
                        <td>${ip}</td>
                        <td>${getFormatTime(date)}</td>
                        <td><span class="a-text">撤销</span></td>
                    </tr>`;
    // 添加到表格
    document.querySelector('#ban-ip table tbody').innerHTML += newRecord;
    // 跳转到最后一行
    document.querySelector('#ban-ip table tbody').lastChild.scrollIntoView({ behavior: 'smooth' });
});

// 监听白名单按钮
document.querySelector('#white-list button').addEventListener('click', function (e) {
    let ip = document.querySelector('#white-list input').value;
    if (!isIp(ip)) {
        alert('IP 地址不合法');
        return;
    }
    // 获取当前时间
    let date = new Date();

    // 添加表格
    let newRecord = `<tr>
                        <td>${ip}</td>
                        <td>${getFormatTime(date)}</td>
                        <td><span class="a-text">撤销</span></td>
                    </tr>`;
    // 添加到表格
    document.querySelector('#white-list table tbody').innerHTML += newRecord;
    // 跳转到最后一行
    document.querySelector('#white-list table tbody').lastChild.scrollIntoView({ behavior: 'smooth' });
});

// 监听撤销按钮
document.getElementById('dialog').addEventListener('click', function (e) {
    if (e.target.closest('.a-text')) {
        e.target.closest('tr').remove();
    }
});

// 判断 ipv4 地址是否合法
function isIp(ip) {
    let a = ip.split('.');
    if (a.length !== 4) {
        return false;
    }
    for (let i = 0; i < 4; i++) {
        if (a[i] === '') {
            return false;
        }
        if (a[i] < 0 || a[i] > 255) {
            return false;
        }
    }

    return true;
}

// 更新本地时间
function updateLocalTime() {
    let date = new Date();
    let time = getFormatTime(date).split(' ');
    document.getElementById('date').innerText = time[0];
    document.getElementById('time').innerText = time[1];
}

// 更新个人信息
function updateUserInfo() {
    // 本地缓存
    let username = localStorage.getItem('username');
    let email = localStorage.getItem('email');
    if (username) {
        document.getElementById('username').innerText = username;
    }
    if (email) {
        document.getElementById('email').innerText = email;
    }

    axiosInstance.get('/user/userInfo')
        .then(response => {
            if (response.data.code === 0) {
                username = response.data.data.username;
                email = response.data.data.email;
                if (username) {
                    localStorage.setItem('username', username);
                    document.getElementById('username').innerText = username;
                }
                if (email) {
                    localStorage.setItem('email', email);
                    document.getElementById('email').innerText = email;
                }
            }
        })
        .catch(error => {
            console.error('获取个人信息失败', error);
        });
}

// 修改密码
function changePassword() {
    let oldPassword = document.getElementById('old-password').value;
    let newPassword = document.getElementById('new-password').value;
    let confirmPassword = document.getElementById('confirm-password').value;
    let error = '';

    if (oldPassword === '' || newPassword === '' || confirmPassword === '') {
        alert('请填写完整信息');
        return;
    }

    if (oldPassword === newPassword) {
        alert('新密码不能与旧密码相同');
        return;
    }

    if (error = validatePassword(oldPassword)) {
        alert(error);
        return;
    }
    if (error = validatePassword(newPassword)) {
        alert(error);
        return;
    }
    if (newPassword !== confirmPassword) {
        alert('两次密码不一致');
        return;
    }

    axiosInstance.patch('/user/updatePwd', {
        old_pwd: oldPassword,
        new_pwd: newPassword,
        re_pwd: confirmPassword
    }).then(response => {
        if (response.data.code === 0) {
            alert('修改密码成功, 请重新登录');
            localStorage.removeItem('lastActiveTime');
            localStorage.removeItem('token');
            window.location.href = './login.html';
        } else {
            alert(response.data.message);
        }
    }).catch(error => {
        console.error('修改密码失败', error);
        alert('修改密码失败');
    });
}

// 修改用户信息
function changeInfo(data) {
    // 获取用户信息
    axiosInstance.get('/user/userInfo')
        .then(response => {
            if (response.data.code === 0) {
                let res = response.data.data;
                // 遍历data对象
                for (let key in data) {
                    res[key] = data[key];
                }
                // 修改用户信息
                axiosInstance.put('/user/update', res)
                    .then(response => {
                        if (response.data.code === 0) {
                            if (res.username) {
                                localStorage.setItem('username', res.username);
                                document.getElementById('username').innerText = res.username;
                            }
                            if (res.email) {
                                localStorage.setItem('email', res.email);
                                document.getElementById('email').innerText = res.email;
                            }
                            alert('修改成功');
                            document.getElementById('dialog').close();
                        } else {
                            alert(response.data.message ? response.data.message : '修改用户信息失败');
                        }
                    })
                    .catch(error => {
                        console.error('修改用户信息失败', error);
                    });
            } else {
                alert(response.data.message ? response.data.message : '获取用户信息失败');
            }
        })
        .catch(error => {
            console.error('获取个人信息失败', error);
        });
}

// 修改邮箱
function changeEmail() {
    let email = document.getElementById('email-input').value;
    let error = '';
    if (email === '') {
        alert('邮箱不能为空');
        return;
    }
    if (error = validateEmail(email)) {
        alert(error);
        return;
    }

    changeInfo({ email: email });
}

// 获取并更新异常列表
function getAndUpdateAnomalyTable() {
    axiosInstance.get('/traffic/filtered-data')
        .then(response => {
            if (response.data.code === 0) {
                // 按时间降序排序
                dataArray = response.data.data.sort((a, b) => {
                    return new Date(b.eventTime) - new Date(a.eventTime)
                });
                if (dataArray?.length !== 0) {
                    document.getElementById('max-page').innerText = Math.ceil(dataArray.length / 10);
                    updateAnomalyTable();
                }
            } else {
                alert(response.data.message ? response.data.message : '获取异常列表失败');
            }
        }).catch(error => {
            console.error('获取异常列表失败', error);
        });
}

// 更新异常列表
function updateAnomalyTable() {
    //dataArray = [{
    //     "destinationPort": "80",
    //     "flowDuration": "36129 ms",
    //     "flowRate": "321985.1089 MB/s",
    //     "packetRate": "193.750173 p/s",
    //     "synFlagCount": "0",
    //     "rstFlagCount": "0",
    //     "ackFlagCount": "0",
    //     "eventTime": "2025-03-12 11:46:43",
    //     "label": "DDoS"
    // }]
    dataArray.sort((a, b) => {
        return new Date(b.eventTime) - new Date(a.eventTime);
    });
    let tbody = document.querySelector('#anomaly-table tbody');
    tbody.innerHTML = '';
    let pageNumber = parseInt(document.getElementById('current-page').innerText);
    for (let index = (pageNumber - 1) * 10; index < pageNumber * 10 && index < dataArray.length; index++) {
        let tr = document.createElement('tr');
        let { destinationPort, flowDuration, flowRate, packetRate, synFlagCount,
            rstFlagCount, ackFlagCount, eventTime, label } = dataArray[index];
        tr.innerHTML =
            `<td title="${destinationPort}">${destinationPort}</td>
            <td title="${flowDuration}">${round(flowDuration)}</td>
            <td title="${flowRate}">${round(flowRate)}</td>
            <td title="${packetRate}">${round(packetRate)}</td>
            <td title="${synFlagCount}">${synFlagCount}</td>
            <td title="${rstFlagCount}">${rstFlagCount}</td>
            <td title="${ackFlagCount}">${ackFlagCount}</td>
            <td title="${eventTime}">${eventTime}</td>
            <td title="${label}">${label}</td>
            <td><span class="a-text" data-index="${index}">详情</span></td>
            `;
        tbody.appendChild(tr);
    }
}

// 四舍五入保留整数
function round(dataString) {
    let [num, unit] = dataString.split(' ');
    num = parseFloat(num);
    if (num > 1000) {
        num = num / 1000;
        switch (unit) {
            case 'MB/s':
                unit = 'GB/s';
                break;
            case 'p/s':
                unit = 'Kp/s';
                break;
            case 'ms':
                unit = 's';
                break;
            default:
                break;
        }
    }
    return Math.round(num) + ' ' + unit;
}

// 更新异常页面
function updateDataMonitor() {
    let now = new Date();
    document.querySelector('#data-monitor tbody tr').children[4].innerText = getFormatTime(now);
}

// 获取异常详情
function getAnomalyDetails(index) {
    const content = document.querySelector('#anomaly-details-content');
    content.innerText = `请求中...`;
    let data = dataArray[index];
    if (!data) {
        content.innerText = '数据丢失，请刷新页面';
        return;
    }
    // 判断是否又缓存
    if (data.details) {
        content.innerText = data.details;
        return;
    }
    // 显示请求中
    let comment = 0;
    const interval = setInterval(() => {
        content.innerText = `请求中...(${comment.toString()})`;
        comment++;
    }, 1000);
    let query = encodeURI('?rawdata=' + JSON.stringify(data)); // 使用 encodeURI 编码，避免特殊字符导致的异常
    axiosInstance.post('/llm/analyze' + query)
        .then(response => {
            if (response.data.code === 0) {
                clearInterval(interval);
                content.innerText = response.data.data;
                data.details = response.data.data;
            } else {
                clearInterval(interval);
                content.innerText = response.data.message;
            }
        }).catch(error => {
            clearInterval(interval);
            content.innerText = '获取异常详情失败';
            console.error('获取异常详情失败', error);
        });
}